package com.aimer.service.impl;

import com.aimer.domain.ResponseResult;
import com.aimer.domain.User;
import com.aimer.domain.UserLogin;
import com.aimer.service.LoginService;
import com.aimer.utils.JwtUtil;
import com.aimer.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        // 判断用户是否存在
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }

        // 使用userId生成token
        UserLogin userLogin = (UserLogin) authenticate.getPrincipal();
        String userId = userLogin.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 将当前登录用户信息存入redis
        redisCache.setCacheObject("login:" + userId,userLogin);

        // 将token返回给前端
        Map<String,String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLogin userLogin = (UserLogin) authentication.getPrincipal();
        Long userId = userLogin.getUser().getId();
        redisCache.deleteObject("login:" + userId);
        return new ResponseResult(200,"退出成功");
    }
}
